<?php
/*name:单位模型
 *time:2017-05-03
 * 王加明
 * 版本：v0.0.1
 * */
namespace app\common\model;
use think\Db;
class Unit
{
    var $chief;
    private $config;
    private $userId;
    private $user;
    private $state_removed = 0;
    private $state_active = 1;
    private $state_sealed = 2;
    private $ultimate;
    private $auth;
    private $prefix;
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    // ------------------------------------------------- 基础支持函数 -------------------------------------------------
    function __construct()
    {
        //获取表前缀
        $this->prefix = config('database.prefix');
        $user = $this->user = new User;
        $this->auth = model('Admin')->is('network')['state'];
        //获取user_id
        if (!$this->userId) {
            $userId = $this->userId = $user->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
        //获取配置文件
        $this->chief = $this->isChief();
        $config = getConfig('admin');
        $this->config = $config;
        $this->isUltimate();
    }

    //辅助函数，获取配置文件
    //参数
    //num：1为修改字段，2为编辑单位信息的必填项，3为邀请时效
    function demand($unit_info, $num)
    {
        if (!$unit_info) {
            return [
                'state' => 0,
                'errormsg' => ' Parameter error'
            ];
        }
        $type = explode(',', $unit_info);
        $config = getConfig('unit');
        $f = [];
        switch ($num) {
            case 1:
                if ($this->auth) {
                    //管理员修改的字段
                    foreach ($type as $k => $v) {
                        foreach ($config as $kk => $vv) {
                            if ($v == $vv['id']) {
                                $f = $vv['modify_admin_not_allowed'];
                            }
                        }
                    }
                    return $f;
                }
                //用户修改的字段
                foreach ($type as $k => $v) {
                    foreach ($config as $kk => $vv) {
                        if ($v == $vv['id']) {
                            $f = $vv['modify_active_not_allowed'];
                        }
                    }
                }
                return $f;
            case 2:
                if ($this->auth) {
                    //管理员邀请的必填项
                    foreach ($type as $k => $v) {
                        foreach ($config as $kk => $vv) {
                            if ($v == $vv['id']) {
                                $f = $vv['required'];
                            }
                        }
                    }
                    return $f;
                }
                //用户申请的必填项
                foreach ($type as $k => $v) {
                    foreach ($config as $kk => $vv) {
                        if ($v == $vv['id']) {
                            $f = $vv['required'];
                        }
                    }
                }
                return $f;
            case 3:
                if ($this->auth) {
                    //管理员邀请时效
                    foreach ($type as $k => $v) {
                        foreach ($config as $kk => $vv) {
                            if ($v == $vv['id']) {
                                $f[] = $vv['invite']['expire'];
                            }
                        }
                    }
                    $pos = array_search(min($f), $f);
                    return $f[$pos];
                }
        }
    }


    //标签
    function label()
    {
        $type = getConfig('unit');
        if (!$type) {
            return array('state' => 0, 'errormsg' => 'config error');
        }
        $label = [];
        $i = 0;
        foreach ($type as $k => $v) {
            $label[$i]['label_id'] = $v['id'];
            $label[$i]['label_text'] = $v['title'];
            $label[$i]['type'] = $k;
            $i++;
        }
        return array('state' => 1, 'data' => ['rank' => $label]);
    }
    //获取用户的单位id
    function getUnitId()
    {
        $where['user_id'] = $this->userId;
        $where['apply'] = 1;
        $res = Db::name('unit')->field('unit_id')->where($where)->find();
        if (!$res) {
            return false;
        }
        return $res['unit_id'];
    }
    //获取当前用户信息
    function getUserInfo($user_id = null)
    {
        if ($user_id == null) {
            $user_id = $this->userId;
        } else {
            $user_id = $user_id;
        }
        $User = new User;
        $userInfo = $User->getInfoById($user_id);
        unset($userInfo['rand_id'],$userInfo['district_modified'],$userInfo['subscribe'],$userInfo['subscribe_time'],$userInfo['birth'],
            $userInfo['last_action'],$userInfo['joint_time'],$userInfo['from'],$userInfo['openid'],$userInfo['headimgurl'],$userInfo['sex'],
            $userInfo['country'],$userInfo['province'],$userInfo['city'],$userInfo['district'],$userInfo['set_name'],$userInfo['user_name']
        );
        return $userInfo;
    }
    //单位是否激活
    function isActive()
    {
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        $where = "user_id=$this->userId";
        $res = Db::name('unit')->field('active')->where($where)->find();
        if ($res['active'] == 1) {
            return array('state' => 1, 'errormsg' => '已开放');
        } else if($res['active'] == 0) {
            return array('state' => 0, 'errormsg' => '未开放');
        }
        if(!$res){
            return array('state'=>0,'errormsg'=>'未找到该单位');
        }
    }


    //用户查看单位信息
    function info()
    {
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => 'please login');
        }
        $where = "user_id=$this->userId and state=1";
        $info = Db::name('unit')->where($where)->find();
        if (!$info) {
            return array('state' => 0, 'errormsg' => 'not find unit');
        }
        $class = explode(',', $info['labels']);
        $type = getConfig('unit');
        foreach ($type as $k => $v) {
            $i = 0;
            foreach ($class as $kk => $vv) {
                if ($vv == $v['id']) {
                    $info['label'][$i]['label_id'] = $v['id'];
                    $info['label'][$i]['labels_name'] = $v['title'];
                    $info['label'][$i]['type'] = $k;
                }
                $i++;
            }
        }
        if($info['apply'] == 5){
            $info['applying'] = 1;
        }
        if($info['apply'] == 4){
            $info['rejected'] = 1;
        }
        if($info['apply'] == 3){
            $info['inviting'] = 1;
        }
        if($info['apply'] == 1){
            $info['editing'] = 1;
        }
        if($info['apply'] == 2){
            $info['invite_overdue'] = 1;
        }
        if($info['apply'] == 0 && $info['release'] == 1){
            $info['released'] = 1;
        }
        if($info['apply'] == 0 && $info['release'] == 0){
            $info['closed'] = 1;
        }
        //单位图片
        if($info['photo_urls']){
            $str = explode(',', $info['photo_urls']);
            $info['photo_url'] = $str;
        }
        //形象人员图片
        if($info['figure']){
            $str = explode(',', $info['figure']);
            $info['figures'] = $str;
        }
        unset($info['photo_urls'],$info['figure'],$info['class'],$info['close'],$info['operator'],$info['invite_id'],$info['exam_id'],$info['state'],$info['active']
        );
        return array('state' => 1, 'data' => ['info' => $info]);
    }
    //邀请单位信息
    function invite_info($token)
    {

        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => 'please login');
        }
        //通过token获取单位id
        $demand = "unit_invite";
        $data = [
            'code' => $token
        ];
        $unit = model('token')->query($demand, $data);
        if (isset($unit['state']) && !$unit['state']) {
            return $unit;
        }
        $unit_id = $unit['data']['content'];
        if (!$unit_id) {
            return array('state' => 0, 'errormsg' => 'not invite_id');
        }
        //检查单位邀请是被撤销
        $where = "unit_id=$unit_id";
        $inviteing = Db::name('unit_invite')->field('inviteing,create_time')->where($where)->find();
        if (!$inviteing) {
            return array('state' => 0, 'errrormsg' => 'not invite');
        }
        if ($inviteing['inviteing'] == 0) {
            return array('state' => 0, 'errrormsg' => 'already cancel');
        }
        //查询单位详细信息
        $where = "a.unit_id = $unit_id and a.active=0";
        $res = Db::name('unit')
            ->alias('a')
            ->join('unit_invite b', 'a.unit_id = b.unit_id')
            ->where($where)
            ->find();
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'Parameter error');
        }
        //检查是否过期
        $time = $_SERVER['REQUEST_TIME'];
        $expire = $this->demand($res['class'], 3);
        if ($time - $inviteing['invite_time'] > $expire) {
            $where = "unit_id=$unit_id";
            $data = [
                'inviteing' => 0,
                'state' => 0
            ];
            $inviteing = Db::name('unit_invite')->where($where)->updata($data);
            $str = "apply = 1";
            Db::name('unit')->where($where)->update($str);
            return array('state' => 0, 'errormsg' => 'already be overdue');
        }
        return array('state' => 1, 'data' => ['info' => $res]);
    }

    //用户申请单位
    function create()
    {
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => 'please loge');
        }
        //管理员创建
        if ($this->auth) {
            $where = "invite_id = " . $this->userId;
            $data['invite_id'] = $this->userId;
            $data['create_time'] = $_SERVER['REQUEST_TIME'];
            $data['state'] = 1;//1为显示,0删除
            $data['active'] = 0;//为未激活
            $data['release'] = 0;//单位默认为不对外开放
            $data['close'] = 1;//解冻状态
            $data['apply'] = 1;//编辑中
            $data['operator'] = $this->userId;
            $res = Db::name('unit')->insert($data);
            if (!$res) {
                return [
                    'state' => 0,
                    'errormsg' => 'false'
                ];
            }
            $result = Db::name('unit')->field('unit_id')->where($where)->order('create_time desc')->find();
            if (!$result) {
                return array('state' => 0, 'errormsg' => 'create false');
            }
            return array('state' => 1, 'errormsg' => 'create success', 'data' => ['unit_id' => $result['unit_id']]);
        }
        //用户创建
        $where = "user_id=" . $this->userId;
        $data['user_id'] = $this->userId;
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        $data['state'] = 1;//1为显示,0删除
        $data['active'] = 0;//为未激活
        $data['release'] = 1;//单位默认为不对外开放
        $data['close'] = 1;//解冻状态
        $data['apply'] = 1;
        $data['operator'] = $this->userId;
        $res = Db::name('unit')->insert($data);
        if (!$res) {
            return [
                'state' => 0,
                'errormsg' => 'false'
            ];
        }
        $result = Db::name('unit')->field('unit_id')->where($where)->order('create_time desc')->find();
        if (!$result) {
            return array('state' => 0, 'errormsg' => 'create false');
        }
        return $result['unit_id'];
    }
    //单位接受邀请
    function accept($token)
    {
        if ($this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        //检查用户是否已经拥有单位了
        $where = "user_id =$this->userId and state = 1 and active = 1";
        $res = Db::name('unit')->where($where)->find();
        if($res){
            return array('state'=>0,'errormsg'=>'该用户已有单位');
        }
        if (!$token) {
            return array('state' => 0, 'errormsg' => '参数错误');
        }
        $demand = "unit_invite";
        $data = [
            'code' => $token
        ];
        $res = model('token')->check($demand, $data);
        if (isset($res['state']) && !$res['state']) {
            return $res;
        }
        $unit_id = $res['data']['content'];
        $user_id = $this->userId;
        $where = "unit_id= $unit_id";
        $data['active'] = 1;
        $data['apply'] = 0;
        $data['user_id'] = $user_id;
        $res = Db::name('unit')->where($where)->update($data);//单位激活
        if ($res) {
            $date['inviteing'] = 0;
            Db::name('unit_invite')->where("unit_id=" . $unit_id)->update($date);//单位激活
            return [
                'state' => 1,
                'errormsg' => '激活成功',
            ];
        }
        return [
            'state' => 0,
            'errormsg' => '激活失败'
        ];
    }
    //用户修改信息
    function modify($unit_id = null, $key, $content)
    {
        //管理员修改
        if ($this->auth) {
            if (!$unit_id) {
                return array('state' => 0, 'errormsg' => '参数错误');
            }
            //查询当前单位状态
            $res = Db::name('unit')->where("unit_id=$unit_id")->find();
            $apply = Db::name('unit_apply')->where("unit_id=$unit_id")->find();
            $invite = Db::name('unit_invite')->where("unit_id=$unit_id")->find();
            $data[$key] = $content;
            //处理中
            if (!$res) {
                return array('state' => 0, 'errormsg' => '未找到该单位');
            }
            if($res['apply'] == 5) {
                return array('state' => 0, 'errormsg' => '申请中');
            }
            if($res['apply'] == 3) {
                return array('state' => 0, 'errormsg' => '邀请中');
            }
            if($res['apply'] == 4) {
                return array('state' => 0, 'errormsg' => '已拒绝');
            }
            if($res['state'] == 0){
                return array('state' => 0, 'errormsg' => '已拒绝');
            }
            if($res['apply'] == 2){
                return array('state' => 0, 'errormsg' => '邀请过期');
            }
            //编辑中
            $where = "unit_id=$unit_id and state=1";
            $result = Db::name('unit')->where($where)->update($data);
            if ($result) {
                return [
                    'state' => 1,
                    'errormsg' => "ok",
                    'unit_id'=>$unit_id
                ];
            }
            //处理后
            if ($res['active'] == 1 and $res['close'] == 1 and $res['state'] == 1) {
                //将字符串转为数组
                $class = $res['labels'];
                $f = $this->demand($class, 1);
                $f = array_keys($f);
                //检查传过来的数据，KEY是否可以修改
                if (!in_array($key, $f)) {
                    return array('state' => 0, 'errormsg' => '参数错误');
                }
                $where = "unit_id=$unit_id and state=1";
                $update = Db::name('unit')->where($where)->update($data);
                if ($update) {
                    return [
                        'state' => 1,
                        'errormsg' => "修改成功",
                        'unit_id'=>$unit_id
                    ];
                }
            }

            return [
                'state' => 0,
                'errormsg' => "修改失败"
            ];
        }
        //用户修改
        //编辑中
        if ($unit_id == null) {
            $unit_id = $this->getUnitId();
            if (!$unit_id) {
                $user_id = $this->userId;
                $unit_id = $this->create($user_id);
            }
            $unit_id = $unit_id;
        } else {
            $unit_id = $unit_id;
        }
        //查询当前单位状态
        $res = Db::name('unit')->where("unit_id=$unit_id")->find();
        if($res['province'] && $res['city'] && $res['district'] && $res['address']){
            $ak='zInrkldrOGmWFcCTSifNBRYfKCDtz199';
            $address = $res['province'].$res['city'].$res['district'].$content;
            $x = file_get_contents("http://api.map.baidu.com/geocoder/v2/?address=$address&output=json&ak=$ak");
            $x = json_decode($x,1);
            if(!$x['status']){
                $a['lng'] = $x['result']['location']['lng'];
                $a['lat'] = $x['result']['location']['lat'];
                $ress = db('unit')->where("unit_id = $unit_id")->update($a);
            }
        }
        $apply = Db::name('unit_apply')->where("unit_id=$unit_id")->find();
        $invite = Db::name('unit_invite')->where("unit_id=$unit_id")->find();
        $data[$key] = $content;
        //处理中
        if (!$res) {
            return array('state' => 0, 'errormsg' => '未找到该单位');
        }
        if (isset($apply) and $apply['applying'] == 1) {
            return array('state' => 0, 'errormsg' => '申请中');
        }
        if (isset($invite) and $invite['inviteing'] == 1) {
            return array('state' => 0, 'errormsg' => '邀请中');
        }
        if (!$res['close']) {
            return array('state' => 0, 'errormsg' => '已关闭');
        }
        $where = "unit_id= $unit_id and state = 1";
        $result = db('unit')->where($where)->update($data);
//        $result = db('user')->select();
        if ($result) {
            return [
                'state' => 1,
                'errormsg' => "ok",
                'unit_id'=>$unit_id

            ];
        }
        //处理后
        if ($res['active'] == 1 and $res['close'] == 1 and $res['state'] == 1) {
            $class = $res['labels'];
            $f = $this->demand($class, 1);
            $f = array_keys($f);
            //检查传过来的数据，KEY是否可以修改
            if (!in_array($key, $f)) {
                return array('state' => 0, 'errormsg' => '参数错误');
            }
            $where = "unit_id=$unit_id and state=1";
            $update = Db::name('unit')->where($where)->update($data);
            if ($update) {
                return [
                    'state' => 1,
                    'errormsg' => "修改成功",
                    'unit_id'=>$unit_id
                ];
            }
        }
        return [
            'state' => 0,
            'errormsg' => "修改失败"
        ];
    }
    //用户点击申请
    function apply()
    {
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        //检查用户是否已经拥有单位了
        $where = "user_id =$this->userId and state = 1 and apply = 1";
        $res = Db::name('unit')->where($where)->find();
        if(!$res){
            return array('state'=>0,'errormsg'=>'申请失败');
        }
        $unit_id = $this->getUnitId();
        if (!$unit_id) {
            return ['state'=>0,'errormsg'=>'未找到您的单位'];
        }
        $data['unit_id'] = $unit_id;
        $data['user_id'] = $this->userId;
        $data['state'] = 1;
        $data['apply_time'] = $_SERVER['REQUEST_TIME'];
        $data['applying'] = 2;//申请中
        $res = Db::name('unit_apply')->insert($data);
        if (!$res) {
            return [
                'state' => 0,
                'errormsg' => '申请失败'
            ];
        }
        $where = "unit_id = $unit_id";
        $str['apply'] = 5;
        Db::name('unit')->where($where)->update($str);
        return [
            'state' => 1,
            'errormsg' => '申请成功'
        ];
    }
    //管理员查看用户申请列表
    function getlist($filter)
    {
        if (!$this->auth) {
            return [
                'state' => 0,
                'errormsg' => "您没有权限"
            ];
        }
        if (isset($filter['page']) && $filter['page'] != '') {
            $page = $filter['page'] - 1;
        } else {
            $page = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        //查询正式单位列表（默认）
        $where = 'state = 1';
        //模糊查询
        if ($filter['keywords']) {
            $where .= " and ".keywordSQL($filter['keywords'], 'unit_name,tel');
            /*$order = "create_time desc";
            $list = Db::name('unit')->where($where)->order($order)->select();
            foreach($list as $k=>$v){
                $where ="unit_id = $v[unit_id]";
                $apply = Db::name('unit_apply')->field('apply_time,applying')->where($where)->find();
                if($apply){
                    $list[$k]['apply'][] = $apply;
                }
                $invite = Db::name('unit_invite')->field('invite_time,inviteing')->where($where)->find();
                if($invite){
                    $list[$k]['invite'][] = $invite;
                }
            }*/
        }
        if ($filter) {
            switch ($filter['unit_state']) {
                //申请中
                case 'applying':
                    $where .= " and apply = 5";
                    /*//查询申请表
                    $list = Db::name('unit_apply')
                        ->alias('a')
                        ->join($this->prefix."unit b","a.unit_id = b.unit_id")
                        ->where($where)
                        ->order($order)
                        ->limit($page * $maxPerPage, $maxPerPage)
                        ->select();*/
                    break;
                //编辑中
                case 'editing':
                    $where .= " and apply = 1 and invite_id = $this->userId";
                    /* $order = "create_time desc";
                     $list = Db::name('unit')
                           ->where($where)
                           ->order($order)
                           ->select();*/
                    break;
                //邀请中
                case 'inviting':
                    $where .= " and apply = 3";
                    /*$order = "a.invite_time desc";
                    //查询邀请表
                    $list = Db::name('unit_invite')
                        ->alias('a')
                        ->join($this->prefix."unit b","a.unit_id = b.unit_id")
                        ->where($where)
                        ->order($order)
                        ->limit($page * $maxPerPage, $maxPerPage)
                        ->select();*/
                    break;
                //拒绝
                case 'rejected':
                    $where .= " and apply = 4";
                    /*$order = "a.apply_time desc";
                    //查询申请表
                    $list = Db::name('unit_apply')
                        ->alias('a')
                        ->join($this->prefix."unit b","a.unit_id = b.unit_id")
                        ->where($where)
                        ->order($order)
                        ->limit($page * $maxPerPage, $maxPerPage)
                        ->select();*/
                    break;
                //邀请过期
                case 'invite_overdue':
                    $time = $_SERVER['REQUEST_TIME'];
                    $invite = Db::name('unit_invite')->where("inviteing=2 and state=1")->select();
                    foreach($invite as $k=>$v){
                        $unit = Db::name('unit')->where("unit_id = $v[unit_id]")->find();
                        $expire = $this->demand($unit['labels'],3);
                        if ($time - $v['invite_time'] > $expire) {
                            $data = [
                                'inviteing' => 0,
                                'state' => 0
                            ];
                            $inviteing = Db::name('unit_invite')->where("unit_id = $v[unit_id]")->update($data);
                            $str =[
                              'apply'=>2
                            ];
                            Db::name('unit')->where($where)->update($str);
                        }
                    }
                    $where .= " and apply = 2";
                    /*$order = "a.invite_time desc";
                    $list = Db::name('unit_invite')
                        ->alias('a')
                        ->join($this->prefix."unit b","a.unit_id = b.unit_id")
                        ->where($where)
                        ->order($order)
                        ->limit($page * $maxPerPage, $maxPerPage)
                        ->select();*/
                    break;
                case 'released':
                    $where .= " and apply = 0 and `release` = 1";
                    break;
                case 'closed':
                    $where .=" and `release` = 0 and apply = 0";
                    break;
            }
        }
        //查询列表（默认）
        $order = "apply desc";
        $list = Db::name('unit')
            ->where($where)
            ->order($order)
            ->limit($page * $maxPerPage, $maxPerPage)
            ->select();
        //添加用户信息
        foreach ($list as $k => $v) {
            $class = explode(',', $v['labels']);
            $type = getConfig('unit');
            foreach ($type as $kk => $vv) {
                $i = 0;
                foreach ($class as $kkk => $vvv) {
                    if ($vvv == $vv['id']) {
                       // $list[$k]['labels'][$i]= $vv['id'];
                        $list[$k]['labels_name'][$i] = $vv['title'];
                        //$list[$k]['label'][$i]['type'] = $kk;
                    }
                    $i++;
                }
            }
            //单位图片
            if($v['photo_urls']){
                $str = explode(',', $v['photo_urls']);
                $list[$k]['photo_url'] = $str;
            }
            //形象人员图片
            if($v['figure']){
                $str = explode(',', $v['figure']);
                $list[$k]['figures'] = $str;
            }
            //用户详细信息
            if ($v['user_id']) {
                $userInfo = $this->getUserInfo($v['user_id']);
                $list[$k]['userInfo'] = $userInfo;
            }
            //如果是拒绝，添加拒绝原因
            if($v['apply'] == 3){
                $where = "unit_id = $v[unit_id]";
                $applying = Db::name('unit_apply')->field('reason')->where($where)->find();
                $list[$k]['reason'] = $applying['reason'];
            }
            if($v['apply'] == 5){
                $list[$k]['applying'] = 1;
            }
            if($v['apply'] == 4){
                $list[$k]['rejected'] = 1;
            }
            if($v['apply'] == 3){
                $list[$k]['inviting'] = 1;
            }
            if($v['apply'] == 1){
                $list[$k]['editing'] = 1;
            }
            if($v['apply'] == 2){
                $list[$k]['invite_overdue'] = 1;
            }
            if($v['apply'] == 0 && $v['release'] == 1){
                $list[$k]['released'] = 1;
            }
            if($v['apply'] == 0 && $v['release'] == 0){
                $list[$k]['closed'] = 1;
            }
        }
        foreach ($list as $key=>$value){
            unset($list[$key]['photo_urls'],$list[$key]['figure'],$list[$key]['close'],$list[$key]['active'],
                  $list[$key]['release'], $list[$key]['operator'],$list[$key]['invite_id'],$list[$key]['exam_id'],$list[$key]['state'],
                  $list[$key]['apply']
            );
        }
        if (!$list) {
            return [
                'state' => 0,
                'errormsg' => '未找到该信息'
            ];
        }
        return [
            'state' => 1,
            'data' => ['list' => $list]
        ];
    }
    //管理员审核用户自主申请
    function apply_handle($unit_id, $authorize, $reason = null)
        {
            if (!$this->auth) {
                return [
                    'state' => 0,
                    'errormsg' => "您没有权限"
                ];
            }
            $data['exam_id'] = $this->userId;//审核者
            $data['operator'] = $this->userId;//操作者
            if ($authorize == 1) {
                $data['active'] = $authorize;
                $data['apply'] = 0;//审核成功
                $where = "unit_id=" . $unit_id;
                //单位激活
                $res = Db::name('unit')->where($where)->update($data);
                if ($res) {
                    //查询userid
                    $date['applying'] = 1;//单位激活
                    Db::name('unit_apply')->where($where)->update($date);//单位激活
                    $unitinfo = db('unit')->where("unit_id = $unit_id")->find();
                    $message['value'][$unitinfo['user_id']] = "您的单位[$unitinfo[unit_name]]审核已通过";
                    $message['title'] = '系统消息';
                    model('message')->send('system',$message,$unitinfo['user_id']);
                    return [
                        'state' => 1,
                        'errormsg' => '激活成功'
                    ];
                }
                return [
                    'state' => 0,
                    'errormsg' => "激活失败"
                ];
            }
            if ($authorize == 0) {
                $data['applying'] = 0;//0为审核失败
                $data['reason'] = $reason;
                $data['state'] = 0;
                $where = "unit_id=$unit_id";
                $res = Db::name('unit_apply')->where($where)->update($data);
                if (!$res) {
                    return [
                        'state' => 0,
                        'errormsg' => "失败"
                    ];
                }
                $str['apply'] = 4;
                Db::name('unit')->where($where)->update($str);
                $unitinfo = db('unit')->where("unit_id = $unit_id")->find();
                $message['value'][$unitinfo['user_id']] = "您的单位[$unitinfo[unit_name]]审核未通过,请修改单位信息后重新提交申请";
                $message['title'] = '系统消息';
                model('message')->send('system',$message,$unitinfo['user_id']);
                return [
                    'state' => 1,
                    'errormsg' => "成功"
                ];
            }
            return [
                'state' => 0,
                'errormsg' => '失败'
            ];

        }
    //邀请单位token
    function invite($unit_id, $email)
        {
            if (!$this->auth) {
                return [
                    'state' => 0,'您没有权限'
                ];
            }
            if (empty($unit_id)) {
                return [
                    'state' => 0,
                    'errormsg' => '参数错误'
                ];
            }
            if (!$email) {
                return [
                    'state' => 0,
                    'errormsg' => '参数错误'
                ];
            }

            //获取配置文件token参数
            $demand = "unit_invite";
            $token = model('Token');
            $data = [
                'content' => $unit_id
            ];
            $token = $token->add($demand, $data);
            if (!$token['state']) {
                return $token;
            }
            foreach ($token as $k => $v) {
                $code = $v['code'];
            }

            //调用邮箱接口向用户发起邀请
            $sendmail = model('email');
            $sendmail = $sendmail->send(
                $demand = "unit_invite",
                $data = array(
                    'code' => $code,
                    'email' => $email
                )
            );
            if (!isset($sendmail['state']) || !$sendmail['state']) {
                return $sendmail;
            }
            if ($sendmail) {
                //添加邀请表数据
                $data['unit_id'] = $unit_id;
                $data['invite'] = $this->userId;
                $data['state'] = 1;//1为显示,0不显示
                $data['inviteing'] = 2;//0失败,1为接受,2正在接收中
                $data['invite_time'] = $_SERVER['REQUEST_TIME'];
                $res = Db::name('unit_invite')->insert($data);
                if (!$res) {
                    return [
                        'state' => 0,
                        'errormsg' => '邀请失败'
                    ];
                }
                $where = "unit_id = $unit_id";
                $str['apply'] = 3;
                Db::name('unit')->where($where)->update($str);
                return [
                    'state' => 1,
                    'errormsg' => '邀请成功'
                ];
            }
            return [
                'state' => 0,
                'errormsg' => '邀请失败'
            ];
        }
    //管理员撤销单位邀请
    function invite_cancel($unit_id)
        {
            if (!$this->auth) {
                return [
                    'state' => 0,
                    'errormsg' => "您没有权限"
                ];
            }
            if (!$unit_id) {
                return [
                    'state' => 0,
                    'errormsg' => "参数错误"
                ];
            }
            $data['state'] = 0;
            $data['inviteing'] = 0;
            $res = Db::name('unit_invite')->where("unit_id=" . $unit_id)->update($data);
            if ($res) {
                $date['state'] = 0;
                $date['operator'] = $this->userId;
                $result = Db::name('unit')->where("unit_id=" . $unit_id)->update($date);
                if ($result) {
                    return [
                        'state' => 1,
                        'errormsg' => "删除成功"
                    ];
                }
            }
            return [
                'state' => 0,
                'errormsg' => "删除是啊比"
            ];
        }


    //单位删除
    function remove($unit_id)
    {
        if (!$this->auth) {
            return [
                'state' => 0,
                'errormsg' => "您没有权限"
            ];
        }
        //单位删除
        $data['state'] = 0;
        $data['operator'] = $this->userId;//操作者
        $where = "unit_id = $unit_id";
        $result = Db::name('unit')->where($where)->update($data);
        if (!$result) {
            return [
                'state' => 0,
                'errormsg' => '删除失败'
            ];
        }
        return [
            'state' => 1,
            'errormsg' => '删除成功'
        ];
    }
    //冻结单位
    function close($unit_id, $close)
    {
        if (!$this->auth) {
            return [
                'state' => 0,
                'errormsg' => "您没有权限"
            ];
        }
        if (!$unit_id > 0) {
            return array('state' => 0, 'errormsg' => '参数错误', 'errorcode' => '');
        }
        if ($close == 1) {
            $data['close'] = 1;
        } else {
            $data['close'] = 0;
        }
        $data['operator'] = $this->userId;//操作者
        $where = "unit_id = $unit_id";
        $result = Db::name('unit')->where($where)->update($data);
        if (!$result) {
            return [
                'state' => 0,
                'errormsg' => '修改失败'
            ];
        }
        return [
            'state' => 1,
            'errormsg' => '修改成功'
        ];
    }
    //单位开/放
    function release($unit_id, $release)
    {
        if (!$unit_id > 0) {
            return array('state' => 0, 'errormsg' => '参数错误', 'errorcode' => '');
        }
        if ($release == 1) {
            $data['state'] = 1;
        } else {
            $data['state'] = 0;
        }
        $data['operator'] = $this->userId;
        $where = "unit_id=" . $unit_id;
        $typeRelease = Db::name('unit')->where($where)->update($data);
        if (!$typeRelease) {
            return array('state' => 0, 'errormsg' => '修改失败');
        }
        return array('state' => 1, 'errormsg' => '修改成功');
    }

    /*********************************单位拥有者对单位的权限分配及管理***********************************************/
    /*********************************单位拥有者对单位的权限分配及管理***********************************************/
    /*********************************单位拥有者对单位的权限分配及管理***********************************************/
    /*********************************单位拥有者对单位的权限分配及管理***********************************************/
    /*********************************单位拥有者对单位的权限分配及管理***********************************************/
    /*********************************单位拥有者对单位的权限分配及管理***********************************************/
    /*********************************单位拥有者对单位的权限分配及管理***********************************************/
    /*********************************单位拥有者对单位的权限分配及管理***********************************************/
    /*********************************单位拥有者对单位的权限分配及管理***********************************************/

    //判断当前用户是否为当前单位的拥有者
    function isUnit($unit_id)
    {
        $user_id = $this->userId;
        if (!$user_id) {
            return false;
        }
        $where = "unit_id = $unit_id";
        $res = Db::name('unit')->where($where)->find();
        if (!$res) {
            return false;
        }
        if ($user_id == $res['user_id']) {
            return $user_id;
        }
        return false;
    }

    private function isChief($user_id = 0)
    {
        if (!$user_id) $user_id = $this->userId;
        $chiefs = getConfig('admin_chief');
        return in_array($user_id, $chiefs);
    }

    private function isUltimate($class = null, $user_id = 0, $unit_id = null)
    {
        if ($this->chief) return true;
        if (!$user_id && !$class && !is_null($this->ultimate)) {
            return $this->ultimate;
        }
        if (!$user_id) $user_id = $this->userId;
        if (!$user_id) {
            return false;
        }
        // $class = pay;
        if ($class) {
            if (is_int($class)) {
                $classId = $class;
            } else {
                $config = $this->config[$class];
                $classId = $config['id'];
                if (!$classId) {
                    return false;
                }
            }
            $where['class'] = $classId;
        }
        $where['ultimate'] = 1;
        $where['state'] = $this->state_active;
        $where['user_id'] = $user_id;
        $where['unit_id'] = $unit_id;
        $res = db('unit_admin')->where($where)->find();
        if ($res) {
            $ultimate = true;
        } else {
            $ultimate = false;
        }
        if (!$class) {
            $this->ultimate = $ultimate;
        }
        return $ultimate;
    }

    private function wechatTag($admin_id, $class)
    {
        $find = db('unit_admin')->where(array('admin_id' => $admin_id))->find();
        $admin_user_id = $find['user_id'];
        $openid = $this->user->getOpenId($admin_user_id);
        $isUltimate = $this->isChief($admin_user_id) || $this->isUltimate(null, $admin_user_id);
        $wechat = new Wechat;
        if ($isUltimate) {
            $wechat->tag_user_add('admin', $openid);
            $tag['admin'] = 1;
        } else {
            $wechat->tag_user_remove('admin', $openid);
            $tag['admin'] = 0;
        }
        $config = getConfig('admin');
        foreach ($config as $key => $value) {
            if ($class == $value['id']) $class = $key;
        }
        $is = $this->is($class, false, $admin_user_id);
        $tag['is'] = $is;
        if ($is['state'] && !isset($is['chief']) && !isset($is['ultimate'])) {
            $res = $wechat->tag_user_add('admin_' . $class, $openid);
        } else {
            $res = $wechat->tag_user_remove('admin_' . $class, $openid);
        }
        $tag['admin_' . $class] = $res;
        // $tag['openid'];
        return $tag;
    }

    //添加
    function search($tel)
    {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$this->chief && !$this->ultimate) {
            return array('state' => 0, 'errormsg' => '您没有权限');
        }
//        $where[] = "TEL = $tel";
//        $field = array("nickname","real_name","headimgurl");
//        $res = M(user)->where($where)->field($field)->find();
        $user = $this->user;
        $res = $user->exist(array('tel' => $tel));
        if (!isset($res['state']) || !$res['state']) {
            return $res;
        }
        $user_id = $res['data']['user_id'];
        $user_info = $user->getInfoById($user_id);
        return array('state' => 1, 'data' => array('info' => $user_info));
    }

    function staff_add($tel, $class, $unit_id)
    {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$class) {
            return array('state' => 0, 'errormsg' => '参数错误');
        }
        $config = $this->config[$class];
        $classId = $config['id'];
        if (!$classId) {
            return array('state' => 0, 'errormsg' => '参数错误');
        }
        if (!$this->chief && !$this->isUltimate($class)) {
            return array('state' => 0, 'errormsg' => '您没有权限');
        }
        //通过tel查找用户是否存在
        $user = $this->user;
        $res = $user->exist(array('tel' => $tel));
        if (!$res['state']) {
            return $res;
        }
        $targetUserId = $res['data']['user_id'];


//        $where[] = "TEL = $tel";
//        $field = array("user_id");
//        $res = M(user)->where($where)->field($field)->find();
//        if(!$res){
//            return array(state=>0,errormsg=>'user not found');
//        }
//        $targetUserId = $res['user_id'];
        //看看是否已经添加了管理员
        $where = array(
            'user_id' => $targetUserId,
            'state' => $this->state_active,
            'class' => $classId,
            'unit_id' => $unit_id
        );
        $res = db('unit_admin')->where($where)->find();
        if ($res) {
            return array('state' => 0, 'errormsg' => '权限已存在', 'data' => array('admin_id' => $res['admin_id']));
        }
        $add = array(
            'user_id' => $targetUserId,
            'state' => $this->state_active,
            'class' => $classId,
            'creator' => $this->userId,
            "create_time" => time(),
            'unit_id' => $unit_id
        );
        $admin_id = db('unit_admin')->insertGetId($add);
        if (!$admin_id) {
            return array('state' => 0, 'errormsg' => '添加失败');
        }
        $tag = $this->wechatTag($admin_id, $class);
        return array('state' => 1, 'tag' => $tag, 'errormsg' => '添加成功', 'data' => array('admin_id' => $res));
    }

    function staff_ultimate($admin_id, $isUltimate, $unit_id)
    {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$this->chief) {
            return array('state' => 0, 'errormsg' => '您没有权限');
        }
        $admin_id = (int)$admin_id;
        if (!$admin_id) {
            return array('state' => 0, 'errormsg' => '权限错误');
        }
        //查找admin存在
        $where = array(
            'admin_id' => $admin_id,
            'unit_id' => $unit_id
        );
        $res = db('unit_admin')->where($where)->find();
        if (!$res) {
            return array('state' => 0, 'errormsg' => '未找到该权限');
        }
        $classId = (int)$res['class'];
        $ultimate = $res['ultimate'];
        $save = array("ultimate" => $isUltimate, 'ultimate_admin_id' => $this->userId, 'ultimate_time' => time());
        $res = db('unit_admin')->where($where)->update($save);
        if (!$res) {
            return array('state' => 1, 'errormsg' => '修改失败');
            // return array('state' => 0, 'errormsg' => 'database save error');
        }
        //wechat tag
        $tag = $this->wechatTag($admin_id, $classId);
        //
        $set = $isUltimate ? 'set' : 'cancel';
        return array('state' => 1, 'tag' => $tag, 'errormsg' => "ultimate $set success");
    }

    function staff_seal($admin_id, $isSeal, $unit_id)
    {

        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        //查找admin存在
        $admin_id = (int)$admin_id;
        if (!$admin_id) {
            return array('state' => 0, 'errormsg' => 'admin id incorrect');
        }
        $where = array(
            'admin_id' => $admin_id,
            'STATE' => ["<>", $this->state_removed],
            'unit_id' => $unit_id
        );
        $res = db('unit_admin')->where($where)->find();
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'admin not found');
        }
        //        if(!$res[seal] && !$cancel){
        //            return array(state=>0,errormsg=>'already sealed');
        //        }
        //        if($res[seal] && $cancel){
        //            return array(state=>0,errormsg=>'not sealed');
        //        }
        $targetUserId = $res['user_id'];
        $targetIsUltimate = (boolean)$res['ultimate'];
        //不能封锁自己
        if (!$this->chief && $this->userId == $targetUserId) {
            return array('state' => 0, 'errormsg' => 'authority incorrect(self)');
        }
        //获取class
        $classId = (int)$res['class'];
        if (!$this->chief && ($targetIsUltimate || !$this->isUltimate($classId))) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        $state_result = $isSeal ? $this->state_sealed : $this->state_active;
        $save = array(
            'state' => $state_result,
            'seal' => $isSeal,
            'seal_admin_id' => $this->userId,
            'seal_time' => time(),
            'unit_id' => $unit_id
        );
        $res = db('unit_admin')->where($where)->update($save);
        if (!$res) {
            return array('state' => 1, 'errormsg' => 'database save nothing');
        }
        //wechat tag
        $tag = $this->wechatTag($admin_id, $classId);
        //
        $seal = $isSeal ? 'seal' : "cancel";
        return array('state' => 1, 'tag' => $tag, 'errormsg' => $seal . ' success');
    }

    //移除
    function staff_remove($admin_id, $unit_id)
    {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        //查找admin存在
        $admin_id = (int)$admin_id;
        if (!$admin_id) {
            return array('state' => 0, 'errormsg' => 'admin id incorrect');
        }
        $where = array(
            'admin_id' => $admin_id,
            'unit_id' => $unit_id
            // 'STATE'         => $this->state_active,
        );
        $res = db('admin')->where($where)->find();
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'admin not found');
        }
        if (!isset($res['state']) || !$res['state']) {
            return array('state' => 0, 'errormsg' => 'already removed');
        }
        $targetUserId = $res['user_id'];
        $targetIsUltimate = (boolean)$res['ultimate'];
        //不能删除自己
        if (!$this->chief && $this->userId == $targetUserId) {
            return array('state' => 0, 'errormsg' => 'authority incorrect(self)');
        }
        //获取class
        $classId = (int)$res['class'];
        if (!$this->chief && ($targetIsUltimate || !$this->isUltimate($classId))) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        $save = array('state' => 0);
        $res = db('unit_admin')->where($where)->update($save);
        if (!$res) {
            // return array('state' => 1, 'errormsg' => 'database save nothing');
            return array('state' => 1, 'errormsg' => 'database save nothing');
        }
        //wechat tag
        $tag = $this->wechatTag($admin_id, $classId);
        //
        return array('state' => 1, 'tag' => $tag, 'errormsg' => 'remove success');
    }

    //列表
    function get_list($unit_id)
    {
        //        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$this->chief && !$this->ultimate) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        $config = $this->config;
        if (!$config) {
            return array('state' => 0, 'errormsg' => 'config incorrect', 'from' => 'admin', 'errorcode' => 101);
            // return array(state => 0, errormsg => 'config incorrect',from=>admin);
        }
        // dump($config);
        foreach ($config as $key => $value) {
            if ($this->isUltimate($key)) {
                $list[$value['id']] = ['class_name' => strtoupper($key)];
                $classIds[] = $value['id'];
            }
        }
        // dump($classIds);
        // dump($list);
        $where = ['state' => ["<>", $this->state_removed], 'class' => ['in', $classIds], 'unit_id' => $unit_id];
        $order = 'seal asc,ultimate desc,create_time desc';
        $res = db('unit_admin')->where($where)->order($order)->select();
        // dump($res);
        $userIds = [];
        foreach ($res as $key => $value) {
            $value['create_time'] = timeString($value['create_time']);
            if ($value['ultimate_time']) $value['ultimate_time'] = timeString($value['ultimate_time']);
            if ($value['seal_time']) $value['seal_time'] = timeString($value['seal_time']);
            $classId = $value['class'];
            $list[$classId]['users'][] = $value;
            $userId = $value['user_id'];
            if ($userId && !in_array($userId, $userIds)) $userIds[] = $userId;
            $userId = $value['creator'];
            if ($userId && !in_array($userId, $userIds)) $userIds[] = $userId;
            $userId = $value['seal_admin_id'];
            if ($userId && !in_array($userId, $userIds)) $userIds[] = $userId;
            $userId = $value['ultimate_admin_id'];
            if ($userId && !in_array($userId, $userIds)) $userIds[] = $userId;
        }
        if (count($userIds)) {
            // dump($userIds);
            $user = $this->user;
            $users = $user->getInfoById($userIds);
            // return ['state'=>1,'data'=>['list'=>$list]];
            $res = db('user_tel')->where(['state' => 1, 'user_id' => ['in', $userIds]])->select();
            foreach ($res as $k => $v) {
                $tels[$v['user_id']] = $v['tel'];
            }
            $res = db('user_email')->where(['state' => 1, 'user_id' => ['in', $userIds]])->select();
            foreach ($res as $k => $v) {
                $emails[$v['user_id']] = $v['email'];
            }
            // dump($users);
            // dump($list);
            foreach ($list as $key => $value) {
                if (!isset($value['users'])) {
                    continue;
                }
                foreach ($value['users'] as $k => $v) {
                    $user_id = $v['user_id'];
                    $user = $users[$user_id];
                    $list[$key]['users'][$k]['user_name'] = (isset($user['set_name']) && $user['set_name']) ? $user['set_name'] : $user['user_name'];
                    $list[$key]['users'][$k]['headimgurl'] = $user['headimgurl'];
                    if (isset($tels[$user_id])) $list[$key]['users'][$k]['tel'] = $tels[$user_id];
                    if (isset($emails[$user_id])) $list[$key]['users'][$k]['email'] = $emails[$user_id];
                    $creator = $users[$v['creator']];
                    $list[$key]['users'][$k]['creator_name'] = isset($creator['set_name']) && $creator['set_name'] ? $creator['set_name'] : $creator['user_name'];
                    if ($v['seal_admin_id']) {
                        $seal_admin = $users[$v['seal_admin_id']];
                        $list[$key]['users'][$k]['seal_admin_name'] = isset($seal_admin['set_name']) && $seal_admin['set_name'] ? $seal_admin['set_name'] : $seal_admin['user_name'];
                    }
                    if ($v['ultimate_admin_id']) {
                        $ultimate_admin = $users[$v['ultimate_admin_id']];
                        $list[$key]['users'][$k]['ultimate_admin_name'] = isset($ultimate_admin['set_name']) && $ultimate_admin['set_name'] ? $ultimate_admin['set_name'] : $ultimate_admin['user_name'];
                    }
                }
            }
        }
        return ['state' => 1, 'data' => ['list' => $list]];
    }

    function list_option()
    {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        $config = $this->config;
        if (!$config) {
            return array('state' => 0, 'errormsg' => 'config incorrect', 'from' => 'admin', 'errorcode' => 'admin2');
        }
        foreach ($config as $key => $value) {
            if ($this->chief || $this->isUltimate($key)) {
                $filter[] = $key;
            }
        }
        if (!isset($filter)) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        return array('state' => 1, 'data' => array('rank' => $filter));
    }

    function menu()
    {
        $user_id = $this->userId;
        if (!$user_id) return ['errormsg' => '请登录'];
        $config = $this->config;
        if (!$config) return ['errormsg' => 'config error', 'errorcode' => 'am91294'];
        $chief = $this->chief;
        if ($chief || $this->isUltimate()) $rank[] = 'manage';
        foreach ($config as $key => $value) {
            $is = $this->is($key);
            if ($chief || (isset($is['state']) && $is['state'])) {
                $rank[] = $key;
            }
        }
        if (!isset($rank)) return ['errormsg' => 'not admin'];
        return ['state' => 1, 'data' => ['rank' => $rank]];
    }

    function exist($user_id = 0)
    {
        if (!$user_id) return false;
        $where = ['user_id' => $user_id, 'state' => $this->state_active];
        $res = db('admin')->where($where)->find();
        if ($res) return true;
        else {
            return false;
        }
    }

    //通用
    function is($demand, $isUltimate = false, $user_id = 0, $unit_id = null)
    {
        if (!$user_id) $user_id = $this->userId;
        if (!$demand) {
            return array('state' => 0, 'errormsg' => 'need demand', 'errorcode' => 'admin43642246');
        }
        //检查权限
        if (!$user_id) {
            return array('state' => 0, 'errormsg' => 'user_id missing', 'errorcode' => 'admin56235235');
        }
        $config = $this->config;
        if (!isset($config)) {
            return array('state' => 0, 'errormsg' => 'config incorrect', 'from' => 'admin', 'errorcode' => 103);
            // return array(state => 0, errormsg => 'config incorrect');
        }
        //class id号输入
        if ($demand == "ultimate") {
            if ($this->isUltimate(null, $user_id)) {
                return array('state' => 1, 'ultimate' => 1);
            }
            if ($this->isChief($user_id)) {
                return array('state' => 1, 'chief' => 1);
            }
            return array('state' => 0, 'errormsg' => 'admin not found');
        } else {
            if (!array_key_exists($demand, $config)) {
                foreach ($config as $key => $value) {
                    if (isset($value['contains'])) {
                        $contains = $value['contains'];
                        if (in_array($demand, explode(",", $contains))) {
                            $classIds[] = $value['id'];
                        }
                    }
                }
            } else {
                $config = $config[$demand];
                $classId = $config['id'];
            }
            if (!isset($classId) && !isset($classIds)) {
                return array('state' => 0, 'errormsg' => 'demand incorrect');
            }
        }
        //看看是否已经添加了管理员
        $where = array(
            'user_id' => $user_id,
            'state' => $this->state_active,
            'unit_id' => $unit_id
        );
        if (isset($classId)) {
            $where['class'] = $classId;
        }
        if (isset($classIds)) {
            $where['class'] = ['in', implode(",", $classIds)];//" `CLASS` in (".implode(",",$classIds).") ";
        }
        if ($isUltimate) {
            $where['ultimate'] = 1;
        }
        $res = db('unit_admin')->where($where)->find();
        if (!$res) {
            if ($this->isChief($user_id)) {
                return array('state' => 1, 'chief' => 1);
            }
            return array('state' => 0, 'errormsg' => 'admin not found');
        }
        return array('state' => 1, 'errormsg' => 'is admin');
    }

    // function getSet($demand, $setting) {
    //     if (!$demand) {
    //         return array('state' => 0, 'errormsg' => 'need demand');
    //     }
    //     if (!$setting) {
    //         return array('state' => 0, 'errormsg' => 'need setting');
    //     }
    //     //检查权限
    //     if (!$this->userId) {
    //         return array('state' => 0, 'errormsg' => '请登录');
    //     }
    //     $config = $this->config;
    //     if (!$config) {
    //         return array('state' => 0, 'errormsg' => 'config incorrect','from'=>'admin','errorcode'=>104);
    //         // return array(state => 0, errormsg => 'config incorrect');
    //     }
    //     $config = $config[$demand];
    //     $classId = $config[id];
    //     if (!$classId) {
    //         return array('state' => 0, 'errormsg' => 'demand incorrect');
    //     }
    //     if (!array_key_exists($setting, $config[setting])) {
    //         return array(state => 0, errormsg => 'setting incorrect');
    //     }
    //     $setting_id = $config[setting][$setting];
    //     //看看是否已经添加了管理员
    //     $where = array(
    //         'a.USER_ID' => $this->userId,
    //         'a.STATE' => $this->state_active,
    //         'a.CLASS' => $classId,
    //         's.KEY_ID' => $setting_id,
    //         );
    //     $order = array("ADMIN_SETTING_ID desc");
    //     $p = C('DB_PREFIX');
    //     $res = M(admin)
    //     ->alias(a)
    //     ->join($p . "admin_setting AS s ON s.ADMIN_ID = a.ADMIN_ID")
    //     ->where($where)
    //     ->order($order)
    //     ->find();
    //     if (!$res) {
    //         return array(state => 0, errormsg => 'setting not found');
    //     }
    //     return array(state => 1, data => array(content => $res[content]));
    // }

    //获取最高权限管理者列表
    function chiefList()
    {
        //检查权限
        if (!$this->userId) {
            return array('state' => 0, 'errormsg' => '请登录');
        }
        if (!$this->chief) {
            return array('state' => 0, 'errormsg' => 'authority incorrect');
        }
        // $config = $this->config;
        // if (!$config) {
        // return array('state' => 0, 'errormsg' => 'config incorrect',from=>admin,errorcode=>105);
        // return array(state => 0, errormsg => 'config incorrect');
        // }
        //获取chief配置文件里的数据
        $chief_ids = getConfig('admin_chief');
        $user = $this->user;
        $info = $user->getInfoById($chief_ids);
        foreach ($info as $key => $value) {
            $user_name = $value['set_name'] ? $value['set_name'] : $value['user_name'];
            $chiefs[] = ['user_name' => $user_name, 'user_id' => $value['user_id']];
        }
        return ['state' => 1, 'data' => ['rank' => $chiefs]];
    }

    //通用
    /*function is($demand, $isUltimate = false, $user_id = 0) {
        if(!$user_id) $user_id = $this->userId;
        if (!$demand) {
            return array('state' => 0, 'errormsg' => 'need demand','errorcode'=>'admin43642246');
        }
        //检查权限
        if (!$user_id) {
            return array('state' => 0, 'errormsg' => 'user_id missing','errorcode'=>'admin56235235');
        }
        $config = $this->config;
        if (!isset($config)) {
            return array('state' => 0, 'errormsg' => 'config incorrect','from'=>'admin','errorcode'=>103);
            // return array(state => 0, errormsg => 'config incorrect');
        }
        //class id号输入
        if($demand == "ultimate"){
            if($this->isUltimate(null,$user_id)){
                return array('state' => 1,'ultimate'=>1);
            }
            if($this->isChief($user_id)){
                return array('state' => 1,'chief'=>1);
            }
            return array('state' => 0, 'errormsg' => 'admin not found');
        }else{
            if(!array_key_exists($demand,$config)){
                foreach ($config as $key => $value) {
                    if(isset($value['contains'])){
                        $contains = $value['contains'];
                        if(in_array($demand,explode(",",$contains))){
                            $classIds[] = $value['id'];
                        }
                    }
                }
            }else{
                $config = $config[$demand];
                $classId = $config['id'];
            }
            if(!isset($classId) && !isset($classIds)){
                return array('state' => 0, 'errormsg' => 'demand incorrect');
            }
        }
        //看看是否已经添加了管理员
        $where = array(
            'user_id' => $user_id,
            'state' => $this->state_active,
        );
        if(isset($classId)){
            $where['class'] = $classId;
        }
        if(isset($classIds)){
            $where['class'] = ['in',implode(",",$classIds)];//" `CLASS` in (".implode(",",$classIds).") ";
        }
        if ($isUltimate) {
            $where['ultimate'] = 1;
        }
        $res = db('unit_admin')->where($where)->find();
        if (!$res) {
            if($this->isChief($user_id)){
                return array('state' => 1,'chief' => 1);
            }
            return array('state' => 0, 'errormsg' => 'admin not found');
        }
        return array('state' => 1, 'errormsg' => 'is admin');
    }*/
    //admin创建单位
    /* function invite_create()
     {
         //创建空单位
         $data['invit'] = $this->userId;
         $data['create_time'] = $_SERVER['REQUEST_TIME'];
         $data['state'] = 2;//2未审核，1为审核,0不显示
         $res = Db::name('unit')->insert($data);
         if (!$res) {
             return [
                 'state' => 0,
                 'errormsg' => 'create false'
             ];
         }
         return [
             'state' => 1,
             'errormsg' => 'create success'
         ];
     }*/

    //admin单位编辑
    /* function unit_modifty($unit_id, $key, $modifyinfo)
     {
         $data[$key] = $modifyinfo;
         $unit_id = addslashes($unit_id); //sql防注入
         $where = "unit_id=$unit_id";
         $res = Db::name('unit_invite')->field('invite_state')->where($where)->order('create_time desc')->find();
         if($res['invite_state'== 2]){//正在接收中都不能修改
             return [
               'state'=>0,
               'errormsg'=>'Accept in.....'
             ];
         }
         if($res['invite_state'] == 1){
             $where = "unit_id=".$unit_id;
             $result = Db::name('unit')->field('class')->where($where)->find();
             //接受后修改的字段
             $config = getConfig("unit_modify");
             foreach ($config as $k=>$v){
                 if($result['class'] == $v['id']){
                     $demand = $k;
                 }
             }
             $f = $config[$demand]['modify_admin_allowed'];
             $f = array_keys($f);
             //检查传过来的数据，KEY是否可以修改
             if (!in_array($key, $f)) {
                 return array('state' => 0, 'errormsg' => 'key incorrect', 'errorcode' => '');
             }
             $where = "unit_id=$unit_id and state=1";
             $res = Db::name('unit')->where($where)->update($data);
             if ($res) {
                 return [
                     'state' => 1,
                     'errormsg' => 'update success'
                 ];
             }
             return [
                 'state' => 0,
                 'errormsg' => 'update false'
             ];
         }
         $where = "unit_id=$unit_id and state=2";
         $res = Db::name('unit')->where($where)->update($data);
         if ($res) {
             return [
                 'state' => 1,
                 'errormsg' => 'update success'
             ];
         }
         return [
             'state' => 0,
             'errormsg' => 'update false'
         ];
     }*/

    //向邀请用户发送邮件
    /*function unit_send($email,$unit_id)
    {
        if(!$unit_id){
            return [
              'state'=>0,
              'errormsg'=>'Parameter error'
            ];
        }
        //获取配置文件token参数
        $demand = "unit_invite";
        $token = model('Token');
        $token = $token->add($demand);
        if(!$token['state']){
            return json($token);
        }
        foreach($token as $k=>$v){
            $code = $v['code'];
        }
        //调用邮箱接口向用户发起邀请
        $sendmail = model('email');
        $sendmail = $sendmail->send(
            $demand = "unit_invite",
            $data = array(
                'code'=>$code,
                'auto'=>$unit_id,
                'email'=>$email
            )
        );
        if (!isset($sendmail['state']) || !$sendmail['state']) {
            return json($sendmail);
        }
        if($sendmail){
            //添加邀请表数据
            $data['unit_id'] = $unit_id;
            $data['invite'] = $this->userId;
            $data['state'] = 1;//1为显示,0不显示
            $data['invite_state'] = 2;//0失败,1为接受,2正在接收中
            $data['create_time'] = $_SERVER['REQUEST_TIME'];
            $res = Db::name('unit_apply')->insert($data);
            if (!$res) {
                return [
                    'state' => 0,
                    'errormsg' => 'invite false'
                ];
            }
            return [
                'state' => 1,
                'errormsg' => 'invite success'
            ];
        }
        return [
            'state' => 0,
            'errormsg' => 'invite false'
        ];
    }*/
}
